package org.itzheng.yuezhi.real.tools.bluetooth;

import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import org.itzheng.yuezhi.R;
import org.itzheng.yuezhi.base.BaseActivity;
import org.itzheng.yuezhi.utils.comm.BlueToothConnUtils;
import org.itzheng.yuezhi.utils.comm.ScreenBroadcastReceiverUtils;
import org.itzheng.yuezhi.utils.comm.ThreadUtils;
import org.itzheng.yuezhi.utils.comm.UIUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by admin on 2017/8/7.
 */

public class BluetoothActivity extends BaseActivity {
    @BindView(R.id.btnSearchBluetooth)
    Button btnSearchBluetooth;
    @BindView(R.id.tvTemp)
    TextView tvTemp;
    @BindView(R.id.tvDamp)
    TextView tvDamp;
    private static final int REQUEST_CODE_SEARCH_BLUETOOTH = 0x001;
    private static final String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";
    private BluetoothSocket socket;
    private InputStream inputStream;
    BlueToothConnUtils blueToothConnUtils = BlueToothConnUtils.getInstance();
    private boolean light1;
    private boolean light2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("蓝牙模块");
        setContentView(R.layout.activity_bluetooth);
        ButterKnife.bind(this);
//        BlueToothBroadcastReceiverUtils.getInstance(this).registerReceiver();
        init();
    }

    private static final String TAG = "BluetoothActivity";

    private void init() {
        ScreenBroadcastReceiverUtils.getInstance(this).addOnSearchBluetoothListener(new ScreenBroadcastReceiverUtils.OnScreenChangeListener() {
            @Override
            public void onScreenOff() {
                Log.e(TAG, "onScreenOff isForeground:" + UIUtils.isForeground(BluetoothActivity.this.getClass()));
            }

            @Override
            public void onScreenOn() {
                Log.e(TAG, "onScreenOn isForeground:" + UIUtils.isForeground(BluetoothActivity.this.getClass()));
            }
        });
        blueToothConnUtils.setOnReceiveListener(new BlueToothConnUtils.OnReceiveListener() {
            @Override
            public void onSuccess(final String s) {
                Log.d(TAG, "onSuccess:" + s.toString());
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        setViewData(s);
                    }
                });
                ThreadUtils.executeDelayed(new Runnable() {
                    @Override
                    public void run() {
                        blueToothConnUtils.getMessage();
                    }
                }, 2000);
            }

            @Override
            public void onError(String s) {
                Log.e(TAG, "" + s);
            }
        });
    }

    private void setViewData(String s) {
        if (s == null || s.isEmpty()) {
            return;
        }
        String[] strings = s.split("T");
        int size = strings == null ? 0 : strings.length;
        for (int i = size < 2 ? 0 : size - 2; i < size; i++) {
            String info = strings[i];
            if (info.length() > 1)
                tvTemp.setText(info.substring(0, 2) + "°C");
            if (info.length() > 3)
                tvDamp.setText(info.substring(2, 4) + "%");
            if (info.length() > 4)
                light1 = (info.substring(4, 5).equals("0"));
            if (info.length() > 5)
                light2 = info.substring(5, 6).equals("0");
        }
    }

    @OnClick({R.id.btnSearchBluetooth, R.id.btnLight1, R.id.btnLight2, R.id.btnClose})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnSearchBluetooth:
                if (true) {
                    Intent intent = new Intent(this, SearchBluetoothActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_SEARCH_BLUETOOTH);
                }
                break;
            case R.id.btnLight1:
                byte buf[] = new byte[3];//开辟3个空间
                buf[0] = (byte) 0x01;//LED1
                buf[1] = light1 ? (byte) 0x00 : (byte) 0x01;//1开灯，0灭灯
                buf[2] = (byte) 0x08;//LED2
                blueToothConnUtils.sendByte(buf, new BlueToothConnUtils.OnSendListener() {
                    @Override
                    public void onSuccess() {
                        UIUtils.showToast("发送成功");
                    }

                    @Override
                    public void onError(String s) {
                        UIUtils.showToast("发送失败");
                    }
                });

                break;
            case R.id.btnLight2:
                byte buf2[] = new byte[3];//开辟3个空间
                buf2[0] = (byte) 0x02;//LED1
                buf2[1] = light2 ? (byte) 0x00 : (byte) 0x01;//1开灯，0灭灯
                buf2[2] = (byte) 0x08;//LED2
                blueToothConnUtils.sendByte(buf2, new BlueToothConnUtils.OnSendListener() {
                    @Override
                    public void onSuccess() {
                        UIUtils.showToast("发送成功");
                    }

                    @Override
                    public void onError(String s) {
                        UIUtils.showToast("发送失败");
                    }
                });
                break;
            case R.id.btnClose:
                blueToothConnUtils.close(new BlueToothConnUtils.OnCloseListener() {
                    @Override
                    public void onSuccess() {
                        UIUtils.showToast("断开成功");
                    }

                    @Override
                    public void onError(String Exception) {
                        UIUtils.showToast("断开失败");
                    }
                });
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_SEARCH_BLUETOOTH:
                if (resultCode == RESULT_OK) {
                    BluetoothDevice device = data.getParcelableExtra(SearchBluetoothActivity.EXTRA_BLUETOOTH_DEVICE);
//                    connect(device);

                    blueToothConnUtils.connectBlueTooth(device, SPP_UUID, new BlueToothConnUtils.OnConnectListener() {
                        @Override
                        public void onSuccess(BluetoothSocket bluetoothSocket) {
                            UIUtils.showToast("连接蓝牙成功");
                            //连接成功则接收消息
                            blueToothConnUtils.getMessage();
                        }

                        @Override
                        public void onError(String error) {
                            UIUtils.showToast("连接蓝牙失败");
                            Log.e(TAG, "onError: " + error);
                        }
                    });
                    UIUtils.showToast(device.getName());
                }
                break;
        }
    }

    public void connect(BluetoothDevice device) {
        try {
            socket = device.createRfcommSocketToServiceRecord(UUID
                    .fromString(SPP_UUID));//通过socket测试是否连接成功
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            socket.connect();
            UIUtils.showToast("连接成功");
        } catch (IOException e) {
            e.printStackTrace();
            UIUtils.showToast("连接失败");
        }
        try {
            inputStream =
                    socket.getInputStream();
            new InputThread().start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private class InputThread extends java.lang.Thread {
        String str;
        //得到一个消息对象，Message类是有Android操作系统提供
        int num;
        private static final String TAG = "InputThread";

        public void run() {
            while (true) {
                Log.d(TAG, "socket.isConnected(): " + socket.isConnected());
                byte buffer[] = new byte[1024];//定义1024个字节
                try {
                    num = inputStream.read(buffer);
                    Log.d(TAG, "num: " + num);
                    str = new String(buffer, 0, num);
                    Message msg = new Message();
                    msg.what = 2;
                    Bundle data = new Bundle();
                    data.putString("msg", str);
                    msg.setData(data);
                    // T318811T318811
                    //格式说明T,分隔符，31，温度，88湿度，1，第一个灯关着，1第2个灯关着
                    Log.d(TAG, "msg: " + str);
//                    mHandler.sendMessage(msg);//发送数据给handler，让其进行数据更新*/
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    //如果发生错误，需要判断是否断开连接，如果断开连接则结束线程，并且给出UI提示
                }
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
